﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.UI.Xaml;
using Newtonsoft.Json;
using Windows.ApplicationModel;
using WinTime.Contracts.Services;
using WinTime.Helpers;
using WinTime.Models;

namespace WinTime.Services;
internal class SettingConfigService : ISettingConfigService
{
    private const string SettingsKey = "AppSettingConfig";
    public SettingConfigModel SettingConfig { get; set; } = new();

    private readonly ILocalSettingsService _localSettingsService;

    public SettingConfigService(ILocalSettingsService localSettingsService)
    {
        _localSettingsService = localSettingsService;
    }


    public async Task InitializeAsync()
    {
        SettingConfig = await LoadConfigFromSettingsAsync();
        // 语言设置
        Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = SettingConfig.Language;
        await Task.CompletedTask;
    }

    private async Task<SettingConfigModel> LoadConfigFromSettingsAsync()
    {
        var config = await _localSettingsService.ReadSettingAsync<SettingConfigModel>(SettingsKey);
        config ??= new SettingConfigModel()
        {
            IsAutoStartup = false
        };
        return config;
    }
    public async Task SetSettingConfigAsync(SettingConfigModel config)
    {
        SettingConfig = config;
        // 开机自启设置
        SelfRunHelper.SetSelfRun(config.IsAutoStartup);
        await SaveConfigInSettingsAsync(config);
    }


    private async Task SaveConfigInSettingsAsync(SettingConfigModel config)
    {
        await _localSettingsService.SaveSettingAsync(SettingsKey, config);
    }
}
